var imgGroupBydictDataKeyUrl = basePath + '/sys/dict/commentTemplate/page';
var imgGroupByIdUrl = basePath + "/sys/dict/commentTemplate/id";
var addUpdateImgGroupUrl = basePath + "/sys/dict/commentTemplate/addUpdate";

var dataDataGrid;
var confirmDialog;
var schoolId = $("#userSchoolId").val();

$(function () {
	initSchoolIdValue();
    initCommentType();
});

function initSchoolIdValue() {
	$("#schoolId").val(schoolId);

}

/**
 * 初始图组位置
 */
function initCommentType() {
    $.ajax({
        url: basePath + "/sys/dict/dictData/dictCode",
        type: 'POST',
        dataType: 'json',
        data: {
            dictCode: 'comment_type',
            schoolId: schoolId
        },
        error: function (data) {
            $.messager.progress('close');
            $.messager.alert('系统提示', data.msg, 'error');
        },
        success: function (data) {
            var currId = $("#dataTypeAllMenu").find("li.dict-cur").find('a').attr("id");
            var html = '';
            data.forEach(function (item, index) {
                var clasz = "";
                if (!currId && index == 0) {
                    clasz = "class=\"dict-cur\"";
                    currId = item.dictDataKey;
                } else {
                    if (item.id == currId) clasz = "class=\"dict-cur\"";
                }
                html += '<li ' + clasz + '><a href="javascript:void(0)" id="' + item.dictDataKey + '" onclick="linkImgGroup(this)" class="tdictType_link">' + item.dictDataValue + '</a></li>'
            });
            initImgGroup(currId);
            $("#dataTypeAllMenu").html(html);
        }
    });

}

/**
 * 菜单数据表
 */
function initImgGroup(dictDataKey) {
    $("#addImgGroup #dictDataKey").val(dictDataKey);
    dataDataGrid = $('#dataGrid').datagrid({
        url: imgGroupBydictDataKeyUrl,
        fit: true,
        fitColumns: true,
        border: true,
        singleSelect: true,
        pagination: true,
        idField: 'id',
        pageSize: 10,
        autoRowHeight: 800,
        pageList: [10],
        nowrap: true,
        striped: true,
        toolbar: '#toolbar',
        queryParams: {
            dictDataKey: dictDataKey,
            schoolId: schoolId
        },
        columns: [[{
            field: 'action',
            title: '操作',
            align: 'center',
            formatter: function (value, row, index) {
                return $.formatString('<button  type="button" class="btn btn-warning btn-xs" style="margin:4px 4px;" onclick="updateImgGroup(\'{0}\');">编辑</button>', row.id);
            }
        }, {
            field: 'id',
            align: 'center',
            title: '<b>编号</b>'
        }, {
            field: 'isValid',
            align: 'center',
            title: '<b>状态</b>',
            formatter: function (value, row, index) {
                if (value == 1) {
                    return "启用";
                }
                return "禁用";
            }
        }, {
            field: 'templateContent',
            align: 'center',
            title: '<b>模板内容</b>',
            width: 20,
            formatter: function (value) {
                return "<a href='javascript:;' title='" + value + "'>" + value + "</a>";
            }
        }, {
            field: 'createTime',
            align: 'center',
            title: '<b>创建时间</b>',
            formatter: function (value) {
                return getTime(value, "yyyy-MM-dd hh:mm");
            }
        }, {
            field: 'updateTime',
            align: 'center',
            title: '<b>修改时间</b>',
            formatter: function (value) {
                return getTime(value, "yyyy-MM-dd hh:mm");
            }
        }
        ]]
    });
}

/**
 * 清空表单
 */
var cleanFormPanel = function (formId) {
    $('#' + formId)[0].reset();
    $('#' + formId + " #imgUrl").val(null);
    $('#' + formId + " #id").val(null);
};

function addImgGroup() {
    $('#addImgGroup').dialog({
        title: $("#addImgGroupForm #id").val() == '' ? '新增模板' : '修改模板',
        modal: true,
        width: 400,
        top: 100,
        draggable: true,
        resizable: true,
        buttons: '#btns',
        onClose: function () {
            cleanFormPanel("addImgGroupForm");
        }
    }).show();
}

function upload() {
    $('#uploadBox').dialog({
        title: '导入模板',
        modal: true,
        width: 400,
        top: 100,
        draggable: true,
        resizable: true,
        buttons: '#btns',
        onClose: function () {
            cleanFormPanel("uploadForm");
        }
    }).show();
}

function updateImgGroup(id) {
    $.ajax({
        url: imgGroupByIdUrl,
        type: "post",
        data: {
            id: id,
			schoolId: schoolId
        },
        dataType: "json",
        async: false,
        success: function (data) {
            addImgGroup();
            $("#addImgGroupForm #id").val(data.id);
            $("#addImgGroupForm #dictDataKey").val(data.dictDataKey);
            $("#addImgGroupForm #templateContent").val(data.templateContent);
            $("#addImgGroupForm #templateContent").val(data.templateContent)
            $("#addImgGroupForm #isValid").val(data.isValid);
        }
    });
}


function commitImgGroup() {
    $.messager.confirm('系统提示', '确认提交吗！', function (r) {
        if (r) {
            $.ajax({
                url: addUpdateImgGroupUrl,
                type: 'POST',
                error: function () {
                    $.messager.progress('close');
                    $.messager.alert('系统提示', '操作异常', 'error');
                },
                data: $('#addImgGroupForm').serialize(),
                success: function (data) {
                    $.messager.progress('close');
                    if (data.code == '000') {
                        $.messager.alert('系统提示', $("#addImgGroupForm #id").val() == '' ? '新增成功' : '修改成功', 'info');
                        initImgGroup($("#dataTypeAllMenu").find("li.dict-cur >a").attr('id'));
                        cleanFormPanel("addImgGroupForm");
                        $('#addImgGroup').dialog('close')
                    } else {
                        $.messager.alert('系统提示', $("#addImgGroupForm #id").val() == '' ? '新增失败' : '修改失败', 'warning');
                    }
                }
            });
        }
    });
}

function linkImgGroup(thiz) {
    var lic = $(thiz.closest('li'));
    if (!lic.hasClass('dict-cur')) {
        initImgGroup(thiz.id);
        lic.addClass("dict-cur").siblings().removeClass("dict-cur");
    }
}


//上传图片
function uploadPic() {
    //上传按钮
    document.querySelector('#regMT-uploadInput').addEventListener('change', function () {
        var that = this;
        var imgWrapObj;
        lrz(that.files[0], {
            width: 1024
        })
        //rst格式
        //rst.origin:图片信息，如大小、日期等
        //rst.base64:生成后的图片base64，后端可以处理此字符串为图片
        //rst.base64Len:生成后的图片的大小，后端可以通过此值来校验是否传输完整
            .then(function (rst) {
                var fileName = rst.origin.name;
                var extName = fileName.substring(fileName.lastIndexOf("."), fileName.length)
                if (!(".jpg|.png|.bmp|.jpeg".toUpperCase().indexOf(extName) == -1)) {
                    alert("只允许上传jpg、png、bmp、jpeg格式的图片");
                    return false;
                }
                extName = extName.substring(1, extName.length);
                $.ajax({
                    type: "post",
                    url: basePath + "/attachment/course/upload/img",
                    data: {
                        extName: extName,
                        imgdata: rst.base64
                    },
                    async: false,
                    cache: false,
                    dataType: "json",
                    success: function (result) {
                        result = result || {};
                        if (result.code == "000") {
                            $("#regMT-uploadPic").attr({
                                "src": imgUrl + result.data + "?v=" + new Date().getTime(),
                                "data-state": "yes"
                            });
                            $("#imgUrl").val(result.data)
                        } else {
                            alert(result.msg);
                        }
                    },
                    error: function () {
                        alert("网络错误！");
                    },
                    beforeSend: function () {
                    },
                    complete: function () {

                    }
                })
            })
            .always(function () {
                // 不管是成功失败，都会执行
            });
    })
}

function uploadCommit() {
    var fileObj = document.getElementById('filebox_file_id_1').files[0];
    var xhr = new XMLHttpRequest();
    xhr.open('POST', basePath + "/sys/file/commentTemplate/import");
    xhr.onload = function () {
        if (xhr.status === 200) {
            var resp = JSON.parse(xhr.response);
            $("#uploadTheFile").val(null);
            if (resp.code == '000') {
                window.location.reload();
            } else {
                alert(resp.msg);
            }
        }
    };
    xhr.onerror = function () {
        alert("上传异常");
    };
    var fd = new FormData();
    fd.append('files', fileObj);
    fd.append("dictDataKey", $("#dictDataKey").val());
    // 触发上传
    xhr.send(fd);
}
